package com.gzhryc.shared_device.common;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.SecurityResponse;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.dictionary.dao.db.Country;
import com.gzhryc.dictionary.dao.db.CountryArea;
import com.gzhryc.dictionary.services.CountryAreaService;
import com.gzhryc.dictionary.services.CountryService;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;

public class CountryAreaUtils {

    static Logger log = Logger.getLogger(CountryAreaUtils.class);
    
    public final static String LocalCountryArea = "localCountryArea" ; 

    static Country country;
    static List<CountryArea> countryAreaList;

    public static void initial(){
    	boolean localCountryArea = PropertyTools.get().getBoolean(LocalCountryArea,false);
    	if(localCountryArea) {
    		//本地管理
    		country = CountryService.self().getOrAddChina();		//获取或创建中国
    		countryAreaList = CountryAreaService.self().findTree(country.getId());
    	}else {
    		//远程管理
	        CountryAreaListResponse apiResp = findCountryAreaList();
	        if(apiResp != null && DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())){
	            country = apiResp.getBody().getCountry();
	            countryAreaList = apiResp.getBody().getCountryAreaList();
	        }else{
	            log.error("初始化国家地区数据失败");
	        }
    	}
    }

    public static Country getCountry(){
        return country;
    }

    public static String getAreaIds(String[] areaNames){
    	if(countryAreaList == null) {
    		//初始化
    		CountryAreaUtils.initial();
    	}
        if(countryAreaList != null && areaNames != null && areaNames.length == 3){
            for(CountryArea province:countryAreaList){
                if(province.getName().equals(areaNames[0])){
                    String areaIds = province.getId().toString();
                    if(province.getChildren() != null && province.getChildren().size() > 0) {
                        for (CountryArea city : province.getChildren()) {
                            if (city.getName().equals(areaNames[1])) {
                                areaIds = areaIds + "," + city.getId();
                                if(city.getChildren() != null && city.getChildren().size() > 0) {
                                    for(CountryArea cityArea : city.getChildren()){
                                        if (cityArea.getName().equals(areaNames[2])) {
                                            areaIds = areaIds + "," + city.getId();
                                            return areaIds;
                                        }
                                    }
                                    log.error("未能获取城区ID，信息：{{0}}",areaNames[2]);
                                }
                                return areaIds;
                            }
                        }
                        log.error("未能获取城市ID，信息：{{0}}",areaNames[1]);
                    }
                    return areaIds;
                }
            }
            log.error("未能获取省ID，信息：{{0}}",areaNames[0]);
        }
        return null;
    }

    public static String[] getAreaNames(String[] areaIds){
    	if(countryAreaList == null) {
    		//初始化
    		CountryAreaUtils.initial();
    	}
        if(countryAreaList != null && areaIds != null && areaIds.length == 3){
            for(CountryArea province:countryAreaList){
                if(province.getId().equals(Long.valueOf(areaIds[0]))){
                    String[] areaNames = new String[3];
                    areaNames[0] = province.getName();
                    if(province.getChildren() != null && province.getChildren().size() > 0) {
                        for (CountryArea city : province.getChildren()) {
                            if (city.getId().equals(Long.valueOf(areaIds[1]))) {
                                areaNames[1] = city.getName();
                                if(city.getChildren() != null && city.getChildren().size() > 0) {
                                    for(CountryArea cityArea : city.getChildren()){
                                        if (cityArea.getId().equals(Long.valueOf(areaIds[2]))){
                                            areaNames[2] = cityArea.getName();
                                            return areaNames;
                                        }
                                    }
                                    log.error("未能获取城区名称，信息：{{0}}",areaIds[2]);
                                }
                                return areaNames;
                            }
                        }
                        log.error("未能获取城市名称，信息：{{0}}",areaIds[1]);
                    }
                    return areaNames;
                }
            }
            log.error("未能获取省名称，信息：{{0}}",areaIds[0]);
        }
        return null;
    }

    public static String[] getAutoAreaNames(String[] areaIds){
    	if(countryAreaList == null) {
    		//初始化
    		CountryAreaUtils.initial();
    	}
        if(countryAreaList != null && areaIds != null && areaIds.length > 0){
            for(CountryArea province:countryAreaList){
                if(province.getId().equals(Long.valueOf(areaIds[0]))){
                    String[] areaNames = new String[3];
                    areaNames[0] = province.getName();
                    if(province.getChildren() != null && province.getChildren().size() > 0 && areaIds.length > 1) {
                        for (CountryArea city : province.getChildren()) {
                            if (city.getId().equals(Long.valueOf(areaIds[1]))) {
                                areaNames[1] = city.getName();
                                if(city.getChildren() != null && city.getChildren().size() > 0 && areaIds.length > 2) {
                                    for(CountryArea cityArea : city.getChildren()){
                                        if (cityArea.getId().equals(Long.valueOf(areaIds[2]))){
                                            areaNames[2] = cityArea.getName();
                                            return areaNames;
                                        }
                                    }
                                    log.error("未能获取城区名称，信息：{{0}}",areaIds[2]);
                                }
                                return areaNames;
                            }
                        }
                        log.error("未能获取城市名称，信息：{{0}}",areaIds[1]);
                    }
                    return areaNames;
                }
            }
            log.error("未能获取省名称，信息：{{0}}",areaIds[0]);
        }
        return null;
    }

    public static CountryArea getProvince(Long provinceId){
    	if(countryAreaList == null) {
    		//初始化
    		CountryAreaUtils.initial();
    	}
        if(countryAreaList != null && provinceId != null) {
            for (CountryArea province : countryAreaList) {
                if (province.getId().equals(provinceId)) {
                    return province;
                }
            }
        }
        return null;
    }

    public static CountryArea getProvince(String provinceName){
    	if(countryAreaList == null) {
    		//初始化
    		CountryAreaUtils.initial();
    	}
        if(countryAreaList != null && StringTools.isNotBlank(provinceName)) {
            for (CountryArea province : countryAreaList) {
                if (province.getName().equals(provinceName)) {
                    return province;
                }
            }
        }
        return null;
    }

    public static List<CountryArea> getCountryAreaList() {
    	if(countryAreaList == null) {
    		//初始化
    		CountryAreaUtils.initial();
    	}
        return countryAreaList;
    }

    /**
     * 获取远程地区数据
     * @return
     */
    private static CountryAreaListResponse findCountryAreaList() {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try {
            URI uri = new URIBuilder("http://www.gzhryc.cn/api/v1/data/country_area/list.data").build();

            httpClient = HttpClients.createDefault();

            HttpPost httpPost = new HttpPost(uri);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                if (JsonTools.isJsonStr(str)) {
                    CountryAreaListResponse apiResp = JsonTools.fromJson(str, CountryAreaListResponse.class);
                    return apiResp;
                }
            }
        } catch (Exception e) {
            log.error("获取国家地区信息错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static class CountryAreaListResponse extends SecurityResponse<CountryAreaListResponse.Body> {

        private static final long serialVersionUID = 1L;

        public CountryAreaListResponse() {
            this.body = new Body();
        }

        public CountryAreaListResponse(Integer code, String msg) {
            super(code,msg);
            this.body = new Body();
        }

        public static class Body implements Serializable {

            private static final long serialVersionUID = 1L;

            private Country country;
            private List<CountryArea> countryAreaList;

            public Country getCountry() {
                return country;
            }

            public void setCountry(Country country) {
                this.country = country;
            }

            public List<CountryArea> getCountryAreaList() {
                return countryAreaList;
            }

            public void setCountryAreaList(List<CountryArea> countryAreaList) {
                this.countryAreaList = countryAreaList;
            }
        }
    }
}
